from rest_framework import serializers
from rest_framework.generics import GenericAPIView
from rest_framework.filters import BaseFilterBackend
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from api import models


class DemoviewSerizer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"

class DemoView(GenericAPIView):
    queryset = models.UserInfo.objects.all()
    serializer_class = DemoviewSerizer
    def get(self, request):
        queryset = self.get_queryset()
        result = self.paginate_queryset(queryset)
        ser = self.get_serializer(instance=result, many=True)
        response = self.get_paginated_response(ser.data)
        return response

class DemoDetailViewSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = ["username","password"]
class MyBaseFilterBackend1(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        id = request.query_params.get('id')
        if not id:
            return queryset
        queryset = queryset.filter(id=id)
        return queryset
class DemoDetailView(ModelViewSet):
    filter_backends = [MyBaseFilterBackend1,]
    queryset = models.UserInfo.objects.all()
    serializer_class = DemoDetailViewSerializer
    def perform_create(self,serializer):
        serializer.save(username="jk",password="123456")
    # def get(self,request,pk):
    #     #1.取数据
    #     obj = self.get_object()
    #     #2.序列化
    #     ser = self.get_serializer(instance=obj,many=True)
    #     return Response(ser.data)